package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishServiceService;

    @Autowired
    private CategoryService categoryService;

    //分页查询
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize,String name){
        Page<Setmeal>pageinfo = new Page<>(page,pageSize);
        Page<SetmealDto>pagedto = new Page<>(page,pageSize);

        LambdaQueryWrapper<Setmeal>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Setmeal::getName,name);

        setmealService.page(pageinfo,queryWrapper);

        BeanUtils.copyProperties(pageinfo,pagedto,"records");

        List<Setmeal> setmeals = pageinfo.getRecords();
        List<SetmealDto>setmealDtos = setmeals.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item,setmealDto);

            Category byId = categoryService.getById(item.getCategoryId());
            setmealDto.setCategoryName(byId.getName());
            return setmealDto;
        }).collect(Collectors.toList());
        pagedto.setRecords(setmealDtos);

        return R.success(pagedto);

    }
    //新增套餐
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)//表示清除所有数据
    public R<String>save(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithdish(setmealDto,0);

        return R.success("新增菜品成功");
    }

    //根据ID查询套餐信息
    @GetMapping("/{id}")
    public R<SetmealDto>get(@PathParam ("ids")@PathVariable Long id){
        if(id == null) return R.error("错误");

        SetmealDto setmealDto = setmealService.useIdtodish(id);


        return R.success(setmealDto);
    }

    //更新
    @PutMapping
    public R<String>update(@RequestBody SetmealDto setmealDto){
        setmealService.saveWithdish(setmealDto,1);
        return R.success("修改成功");
    }

    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)//表示清除所有数据
    public R<String>delete(@RequestParam("ids") List<Long> id){
        if(id.isEmpty()){
            return R.error("没有该套餐");
        }
        id.stream().forEach((item)->{
            setmealService.delete(item);
        });


        return R.success("删除成功");


    }
    //停售/起售菜品，当套餐内菜品停售，套餐也会停售
    @PostMapping("/status/{status}")
    public R<String>unsale(@PathVariable Integer status,@RequestParam("ids") List<Long> id){
        //log.info("statis : {}     id:  {}",status,id);
        if(id.isEmpty() || status == null){
            return R.error("没有该套餐");
        }
        id.stream().forEach((item)->{
            Setmeal byId = setmealService.getById(item);
            if (byId != null) {

                byId.setStatus(status);
                setmealService.updateById(byId);
            }

        });

        return R.success("修改成功");
    }

    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<SetmealDto>> list(Setmeal setmeal) {
        Long categoryId = setmeal.getCategoryId();
        //log.info("cid:   {}", categoryId);
        if (categoryId == null) return R.error("错误");
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId, categoryId);

        List<Setmeal> list = setmealService.list(queryWrapper);

        List<SetmealDto> listDto = list.stream().map((item)->{
            SetmealDto setmealDto = new SetmealDto();

            BeanUtils.copyProperties(item,setmealDto);
            Long categoryId1 = item.getCategoryId();//分类ID
            //根据id查询分类对象
            Category byId = categoryService.getById(categoryId1);
            String name1 = byId.getName();
            setmealDto.setCategoryName(name1);

            //当前菜品ID
            Long setmealId = item.getId();

            LambdaQueryWrapper<SetmealDish>dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(SetmealDish::getSetmealId,setmealId);
            List<SetmealDish> dishFlavorList = setmealDishServiceService.list(dishFlavorLambdaQueryWrapper);
            setmealDto.setSetmealDishes(dishFlavorList);

            return setmealDto;

        }).collect(Collectors.toList());


        return R.success(listDto);
    }


}
